﻿using System.Windows;
using ScrobbleItSL.LastFmApi;
using ScrobbleItSL.Models;
using ScrobbleItSL.ViewModelUtils;

namespace ScrobbleItSL.ViewModels
{
    public class AppViewModel : ViewModelBase
    {
        public const string AuthViewMode = "UserAuth";
        public const string ScrobbleViewMode = "Scrobble";
        
        private readonly IUserModel userModel;
        private readonly LastFmSimpleClient lastFm;

        private string currentView;

        public ViewModelCommand LoginUser { get; set; }

        public AppViewModel() : this(new UserModel())
        {
        }

        public AppViewModel(IUserModel userModel)
        {
            this.userModel = userModel;

            CurrentView = AuthViewMode;

            lastFm = new LastFmSimpleClient();
            LoginUser = new ViewModelCommand(
                o => AuthUser(),
                o =>
                !string.IsNullOrWhiteSpace( UserModel.User.Login ) &&
                !string.IsNullOrWhiteSpace( UserModel.User.Password ) );

            userModel.UserAuthenticated +=
                (sender, args) => Deployment.Current.Dispatcher.BeginInvoke(() => CurrentView=ScrobbleViewMode);
            userModel.AuthenticationFailed += (sender, args) => Deployment.Current.Dispatcher.BeginInvoke(()=>MessageBox.Show("Error: " + args.Message));
        }

        public IUserModel UserModel
        {
            get { return userModel; }
        }

        #region ViewProperties
        public string Login
        {
            get { return userModel.User.Login; }
            set
            {
                userModel.User.Login = value;
                OnPropertyChanged("Login");
                LoginUser.OnCanExecuteChanged();
            }
        }

        public string Password
        {
            get { return userModel.User.Password; }
            set
            {
                userModel.User.Password = value;
                OnPropertyChanged("Password");
                LoginUser.OnCanExecuteChanged();
            }
        }

        public string CurrentView
        {
            get { return currentView; }
            set 
            { 
                currentView = value;
                OnPropertyChanged("CurrentView");
            }
        }

        #endregion

        #region Methods

        public void AuthUser()
        {
            lastFm.AuthMobileSession(UserModel.User, UserModel.OnUserAuthenticated, UserModel.OnAuthenticationFailed);
        }

        #endregion
    }
}
